package com.risk.management.controller;

import com.risk.management.entity.RiskAttachment;
import com.risk.management.service.RiskAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/risk-attachments")
public class RiskAttachmentController {

    @Autowired
    private RiskAttachmentService riskAttachmentService;

    /**
     * 上传风险附件
     */
    @PostMapping("/{riskId}/upload")
    public RiskAttachment uploadAttachment(
            @PathVariable Long riskId,
            @RequestParam("file") MultipartFile file,
            @AuthenticationPrincipal UserDetails userDetails) {
        return riskAttachmentService.uploadAttachment(riskId, file, userDetails.getUsername());
    }

    /**
     * 获取风险的所有附件
     */
    @GetMapping("/{riskId}")
    public List<RiskAttachment> getAttachments(@PathVariable Long riskId) {
        return riskAttachmentService.getAttachmentsByRiskId(riskId);
    }

    /**
     * 下载附件
     */
    @GetMapping("/download/{attachmentId}")
    public ResponseEntity<Resource> downloadAttachment(@PathVariable Long attachmentId) {
        try {
            RiskAttachment attachment = riskAttachmentService.getAttachmentById(attachmentId);
            if (attachment == null) {
                return ResponseEntity.notFound().build();
            }
            
            Path path = Paths.get(attachment.getFilePath());
            Resource resource = new UrlResource(path.toUri());
            
            if (!resource.exists() || !resource.isReadable()) {
                throw new RuntimeException("文件不存在或无法读取");
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(attachment.getFileType()))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + attachment.getOriginalFileName() + "\"")
                    .body(resource);
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
    }

    /**
     * 删除附件
     */
    @DeleteMapping("/{attachmentId}")
    public ResponseEntity<Void> deleteAttachment(@PathVariable Long attachmentId) {
        boolean success = riskAttachmentService.deleteAttachment(attachmentId);
        return success ? ResponseEntity.ok().build() : ResponseEntity.notFound().build();
    }
} 